const multer = require('multer');
const path = require('path');

// 定义允许的文件类型
const allowedFileTypes = {
  image: ['.jpg', '.jpeg', '.png', '.gif'],
  document: ['.pdf', '.doc', '.docx', '.txt'],
  video: ['.mp4', '.avi', '.mov']
};

// 配置存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  const ext = path.extname(file.originalname).toLowerCase();
  const isAllowed = Object.values(allowedFileTypes).flat().includes(ext);
  
  if (isAllowed) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件类型'));
  }
};

// 创建 multer 实例
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 20 * 1024 * 1024, // 5MB
    files: 5 // 最多5个文件
  }
});

module.exports = {
  upload,
  allowedFileTypes
};